<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Video Detail</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body, html { background: #18181a !important; color: #fff; overflow-x: hidden; }
        .video-bg {
            position: relative;
            width: 100vw;
            height: 100vh;
            background: #222;
            overflow: hidden;
        }
        .video-bg-img {
            width: 100vw;
            height: 100vh;
            object-fit: cover;
            filter: brightness(0.55);
        }
        .video-bg-overlay {
            position: absolute; left: 0; top: 0; width: 100%; height: 100%;
            background: linear-gradient(90deg, #18181a 0%, #18181aa0 40%, #18181a00 100%);
        }
        .video-main-info {
            position: absolute; left: 0; top: 0; width: 100%; height: 100%;
            display: flex; flex-direction: column; justify-content: center; padding-left: 80px; z-index: 2;
        }
        .video-title {
            font-size: 2.6em; font-weight: bold; letter-spacing: 0.01em; margin-bottom: 10px;
            max-width: 65vw;
            word-break: break-word;
            margin-right: 32px;
        }
        .video-meta { color: #eee; font-size: 1.1em; margin-bottom: 10px; }
        .video-desc {
            color: #ccc; font-size: 1.08em; max-width: 700px; margin-bottom: 18px;
            display: -webkit-box;
            -webkit-line-clamp: 4;
            -webkit-box-orient: vertical;
            overflow: hidden;
            position: relative;
            transition: max-height 0.2s;
        }
        .video-desc.expanded {
            -webkit-line-clamp: unset;
            max-height: none;
            overflow: visible;
        }
        #descMoreBtnWrap {
            margin-top: 2px;
            margin-bottom: 10px;
            display: none;
        }
        #descMoreBtn {
            background: none;
            border: none;
            color: #4ea3ff;
            font-size: 1em;
            cursor: pointer;
            margin-top: 4px;
            margin-left: 0;
            padding: 0;
            display: none;
        }
        .video-platforms { display: flex; gap: 12px; margin-bottom: 18px; }
        .video-platform-btn { background: #222; border: none; border-radius: 8px; padding: 8px 16px; color: #fff; font-size: 1.1em; display: flex; align-items: center; gap: 8px; transition: background 0.2s; }
        .video-platform-btn img { width: 32px; height: 32px; border-radius: 6px; }
        .video-platform-btn:hover { background: #444; }
        .video-section { margin: 0 auto; max-width: 1400px; padding: 0 40px; }
        .morelike-title { color: #fff; font-size: 1.1em; font-weight: bold; margin: 32px 0 12px 0; }
        .morelike-list {
            display: flex; gap: 18px; overflow-x: auto; padding-bottom: 8px; margin-bottom: 18px;
            scrollbar-width: thin; scrollbar-color: #444 #222;
        }
        .morelike-list::-webkit-scrollbar {
            height: 8px; background: #222; border-radius: 6px;
        }
        .morelike-list::-webkit-scrollbar-thumb {
            background: #444; border-radius: 6px;
        }
        .morelike-list::-webkit-scrollbar-thumb:hover {
            background: #666;
        }
        .morelike-item { width: 400px; min-width: 400px; background: #222; border-radius: 12px; overflow: hidden; margin-bottom: 8px; cursor: pointer; transition: box-shadow 0.18s, transform 0.18s; border: 2px solid transparent; }
        .morelike-item.selected { border: 2px solid #fff; }
        .morelike-item img { width: 100%; height: 225px; object-fit: cover; }
        .morelike-item .morelike-caption { color: #fff; font-size: 1em; font-weight: 500; padding: 8px 12px 0 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .morelike-item .morelike-meta { color: #bbb; font-size: 0.97em; padding: 0 12px 8px 12px; }
        .morelike-item .morelike-duration { color: #aaa; font-size: 0.92em; padding: 0 12px 8px 12px; }
        .video-actions { display: flex; gap: 16px; margin-bottom: 8px; }
        .video-action-btn { background: #222; border: none; border-radius: 12px; padding: 10px 16px; color: #fff; font-size: 1.2em; display: flex; align-items: center; gap: 8px; transition: background 0.2s; }
        .video-action-btn img { width: 28px; height: 28px; border-radius: 6px; }
        .video-action-btn:hover { background: #444; }
        .video-action-label { font-size: 0.98em; color: #ccc; margin-top: 2px; }
        @media (max-width: 900px) {
            .video-main-info { padding-left: 24px; }
            .video-section { padding: 0 10px; }
        }
    </style>
</head>
<body>
    <div class="video-bg">
        <img class="video-bg-img" id="videoBgImg" src="" alt="">
        <div class="video-bg-overlay"></div>
        <div class="video-main-info">
            <div class="video-title" id="videoTitle">Video Title</div>
            <div class="video-meta" id="videoMeta"></div>
            <div class="video-desc" id="videoDesc"></div>
            <div id="descMoreBtnWrap"><span id="descMoreBtn" style="color:#4ea3ff;cursor:pointer;">more</span></div>
            <div class="video-actions" id="videoActions"></div>
            <div class="video-platforms" id="videoPlatforms"></div>
        </div>
    </div>
    <div class="video-section">
        <div class="morelike-title">More Like This</div>
        <div class="morelike-list" id="morelikeList"></div>
        <div class="morelike-meta" id="morelikeMeta"></div>
    </div>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    // ========== 工具 ==========
    function getQueryParam(name) {
        const url = window.location.search;
        const params = new URLSearchParams(url);
        return params.get(name);
    }
    function buildApiUrl(token, value) {
        return `https://saas.zeasn.tv/sp/api/device/v1/column/resourceDetail?token=${encodeURIComponent(token)}&resourceType=12&value=${encodeURIComponent(value)}&needPoster=true&posterWidth=1280&needAward=true`;
    }
    // ========== 数据加载 ==========
    async function loadVideoDetail() {
        const token = getQueryParam('token');
        const value = getQueryParam('value');
        if (!token || !value) {
            $('#videoTitle').text('Missing parameters, unable to load video details');
            return;
        }
        const API_URL = buildApiUrl(token, value);
        let currentVideoId = '';
        try {
            const res = await fetch(API_URL);
            const data = await res.json();
            if (!data.data) {
                $('#videoTitle').text('Failed to get video details');
                return;
            }
            const d = data.data;
            // 获取当前视频id，使用字符串处理避免精度丢失
            try {
                const decodedValue = decodeURIComponent(value);
                // 使用正则表达式提取 id，避免 JSON.parse 精度丢失
                const idMatch = decodedValue.match(/"id":(\d+)/);
                if (idMatch) {
                    currentVideoId = idMatch[1]; // 直接使用字符串，不转换为数字
                } else {
                    currentVideoId = String(d.id);
                }
            } catch(e) { 
                currentVideoId = String(d.id); 
            }
            // 顶部大图
            const poster = (d.posters && d.posters[0] && d.posters[0].url) || (d.covers && d.covers[0] && d.covers[0].url) || '';
            $('#videoBgImg').attr('src', poster);
            // 标题
            $('#videoTitle').text(d.name || '');
            // meta
            let metaArr = [];
            if (d.releaseTime) {
                const dt = new Date(Number(d.releaseTime));
                if (!isNaN(dt.getTime())) metaArr.push(dt.getFullYear());
            }
            if (d.duration) {
                const h = Math.floor(d.duration/60);
                const m = d.duration%60;
                metaArr.push(`${h}:${m.toString().padStart(2,'0')}`);
            }
            if (d.views) metaArr.push(`Views: ${d.views}`);
            if (d.originLangs && d.originLangs.length > 0) metaArr.push(d.originLangs.join(', '));
            $('#videoMeta').text(metaArr.join(' • '));
            // 简介
            let descText = d.description || '';
            function handleDescCollapse() {
                const $desc = $('#videoDesc');
                const $btnWrap = $('#descMoreBtnWrap');
                const $btn = $('#descMoreBtn');
                $desc.data('full', descText);
                function update(expanded) {
                    $desc.toggleClass('expanded', expanded);
                    $btn.text(expanded ? 'less' : 'more');
                }
                // 先展开测真实行数
                $desc.text(descText);
                $desc.addClass('expanded');
                $btnWrap.hide();
                $btn.hide();
                setTimeout(() => {
                    // 获取真实高度和单行高度
                    const realHeight = $desc[0].scrollHeight;
                    $desc.removeClass('expanded');
                    // 现在是省略状态，测省略高度
                    const clampHeight = $desc[0].clientHeight;
                    // 重新展开测单行高度
                    $desc.addClass('expanded');
                    $desc[0].style.webkitLineClamp = 'unset';
                    const lineHeight = parseFloat(window.getComputedStyle($desc[0]).lineHeight);
                    const lines = Math.round(realHeight / lineHeight);
                    $desc.removeClass('expanded');
                    $desc[0].style.webkitLineClamp = '';
                    update(false);
                    if (lines > 4) {
                        $btnWrap.show();
                        $btn.show();
                        $btn.off('click').on('click', function() {
                            update(!$desc.hasClass('expanded'));
                        });
                    } else {
                        $btnWrap.hide();
                        $btn.hide();
                    }
                }, 100);
            }
            handleDescCollapse();
            // 平台按钮
            $('#videoPlatforms').empty();
            if (Array.isArray(d.deeplinks) && d.deeplinks.length > 0) {
                d.deeplinks.forEach(link => {
                    const icon = link.sourceIcon || '';
                    const name = link.sourceName || '';
                    $('#videoPlatforms').append(`<button class='video-platform-btn'><img src='${icon}'><span>${name}</span></button>`);
                });
            }
            // 视频操作按钮（如点赞、评论、分享等）
            $('#videoActions').empty();
            // 2. 删除 More Like This 区域卡片下方的标题/描述渲染
            // 在渲染 morelike-list 区域卡片时，不再插入 <div class="morelike-title">...</div> 或描述相关内容。
            // More Like This
            loadMoreLikeThis(token, value);
        } catch (e) {
            $('#videoTitle').text('加载失败');
        }
    }
    async function loadMoreLikeThis(token, videoValue) {
        $('#morelikeList').empty().append('<div style="color:#aaa;padding:32px 0;">Loading...</div>');
        if (!token || !videoValue) return;
        let videoId = '';
        try {
            // 智能解码：尝试多次解码直到无法继续
            let decodedValue = videoValue;
            let decodeCount = 0;
            const maxDecodes = 3;
            while (decodeCount < maxDecodes) {
                try {
                    const testDecode = decodeURIComponent(decodedValue);
                    if (testDecode === decodedValue) {
                        break;
                    }
                    decodedValue = testDecode;
                    decodeCount++;
                } catch(e) {
                    break;
                }
            }
            // 方法1: 尝试直接解析 JSON
            try {
                const parsed = JSON.parse(decodedValue);
                if (parsed && parsed.id !== undefined) {
                    videoId = String(parsed.id);
                }
            } catch(jsonError) {
                // 方法2: 尝试正则表达式提取
                let idMatch = decodedValue.match(/"id":\s*(\d+)/);
                if (!idMatch) {
                    idMatch = decodedValue.match(/"id"\s*:\s*(\d+)/);
                }
                if (!idMatch) {
                    idMatch = decodedValue.match(/id["\s]*:["\s]*(\d+)/);
                }
                if (!idMatch) {
                    idMatch = decodedValue.match(/id["\s]*:["\s]*[\"]*(\d+)[\"]*/);
                }
                if (!idMatch) {
                    idMatch = decodedValue.match(/id["\s]*:["\s]*(\d+)/i);
                }
                if (!idMatch) {
                    idMatch = decodedValue.match(/"id":\s*"?(\d+)"?/);
                }
                if (idMatch) {
                    videoId = idMatch[1];
                }
            }
            if (!videoId) {
                console.error('无法从 videoValue 中提取 id');
                // 备用方案：尝试从URL中直接提取数字作为ID
                const urlMatch = window.location.search.match(/[?&]value=([^&]+)/);
                if (urlMatch) {
                    const urlValue = urlMatch[1];
                    const numberMatch = urlValue.match(/(\d+)/);
                    if (numberMatch) {
                        videoId = numberMatch[1];
                    }
                }
                if (!videoId) {
                    $('#morelikeList').html('<div style="color:#ff6666;padding:32px 0;">无法提取视频ID</div>');
                    return;
                }
            }
        } catch(e) {
            console.error('解析 videoValue 失败:', e);
            $('#morelikeList').html('<div style="color:#ff6666;padding:32px 0;">解析视频参数失败</div>');
            return;
        }
        const url = `https://saas.zeasn.tv/sp/api/device/v1/video/recommend?token=${encodeURIComponent(token)}&videoType=VIDEO&size=10&needPoster=true&imgStyle=1&videoId=${encodeURIComponent(videoId)}`;
        try {
            const res = await fetch(url);
            const data = await res.json();
            if (!data.data || !Array.isArray(data.data) || data.data.length === 0) {
                $('#morelikeList').html('<div style="color:#aaa;padding:32px 0;">暂无推荐</div>');
                return;
            }
            $('#morelikeList').empty();
            data.data.forEach(item => {
                // 结构与 movie-detail.html 完全一致
                const img = item.poster || item.icon || '';
                const title = item.name || '';
                // categories 展示
                let categoriesStr = '';
                if (item.moreInfo && Array.isArray(item.moreInfo.categories) && item.moreInfo.categories.length > 0) {
                    categoriesStr = `<div style='color:#ffb84d;font-size:0.97em;padding:0 12px 2px 12px;'>${item.moreInfo.categories.map(c => c.name).join(' / ')}</div>`;
                } else if (Array.isArray(item.categories) && item.categories.length > 0) {
                    categoriesStr = `<div style='color:#ffb84d;font-size:0.97em;padding:0 12px 2px 12px;'>${item.categories.join(' / ')}</div>`;
                }
                // videoScores 展示
                let videoScoresStr = '';
                if (item.moreInfo && Array.isArray(item.moreInfo.videoScores) && item.moreInfo.videoScores.length > 0) {
                    videoScoresStr = `<div style='color:#ffd580;font-size:0.97em;padding:0 12px 2px 12px;'>${item.moreInfo.videoScores.map(vs => `${vs.type||''}: ${vs.value||''}`).join(' / ')}</div>`;
                } else if (Array.isArray(item.videoScores) && item.videoScores.length > 0) {
                    videoScoresStr = `<div style='color:#ffd580;font-size:0.97em;padding:0 12px 2px 12px;'>${item.videoScores.map(vs => `${vs.name||''}: ${vs.score||''}`).join(' / ')}</div>`;
                }
                // seasonNumber / episodeCount 展示（仅SEASON类型）
                let seasonNumber = '';
                let episodeCount = '';
                if (item.seasonNumber !== undefined) {
                    seasonNumber = item.seasonNumber;
                } else if (item.moreInfo && item.moreInfo.seasonNumber !== undefined) {
                    seasonNumber = item.moreInfo.seasonNumber;
                } else if (item.value) {
                    try {
                        const v = typeof item.value === 'object' ? item.value : JSON.parse(item.value);
                        if (v.seasonNumber !== undefined) seasonNumber = v.seasonNumber;
                    } catch(e){}
                }
                if (item.episodeCount !== undefined) {
                    episodeCount = item.episodeCount;
                } else if (item.moreInfo && item.moreInfo.episodeCount !== undefined) {
                    episodeCount = item.moreInfo.episodeCount;
                } else if (item.value) {
                    try {
                        const v = typeof item.value === 'object' ? item.value : JSON.parse(item.value);
                        if (v.episodeCount !== undefined) episodeCount = v.episodeCount;
                    } catch(e){}
                }
                let isSeasonType = (item.objectType === 'SEASON' || (item.value && typeof item.value === 'object' && item.value.objectType === 'SEASON'));
                let seasonInfoStr = '';
                if (isSeasonType && (seasonNumber || episodeCount)) {
                    let arr = [];
                    if (seasonNumber) arr.push('S' + seasonNumber);
                    if (episodeCount) arr.push(episodeCount + ' episodes');
                    seasonInfoStr = `<div style='color:#ffd580;font-size:0.97em;padding:0 12px 2px 12px;'>${arr.join(' / ')}</div>`;
                }
                // duration 展示
                let duration = '';
                if (item.duration !== undefined) {
                    duration = item.duration;
                } else if (item.moreInfo && item.moreInfo.duration !== undefined) {
                    duration = item.moreInfo.duration;
                } else if (item.value) {
                    try {
                        const v = typeof item.value === 'object' ? item.value : JSON.parse(item.value);
                        if (v.duration !== undefined) duration = v.duration;
                    } catch(e){}
                }
                function formatDuration(d) {
                    d = Number(d);
                    if (isNaN(d) || d <= 0) return '';
                    const h = Math.floor(d / 3600);
                    const m = Math.floor((d % 3600) / 60);
                    const s = d % 60;
                    let arr = [];
                    if (h > 0) arr.push(h + 'h');
                    if (m > 0) arr.push(m + 'm');
                    if (s > 0 || arr.length === 0) arr.push(s + 's');
                    return arr.join(' ');
                }
                let durationStr = '';
                if (duration) {
                    durationStr = `<div style='color:#ffd580;font-size:0.97em;padding:0 12px 2px 12px;'>${formatDuration(duration)}</div>`;
                }
                // value展示
                const valueStr = item.value ? `<div style='color:#bbb;font-size:0.92em;word-break:break-all;padding:0 12px 2px 12px;'>${item.value}</div>` : '';
                // deeplinkDetailList展示
                let deeplinkHtml = '';
                if (Array.isArray(item.deeplinkDetailList) && item.deeplinkDetailList.length) {
                    deeplinkHtml = `<div style='display:flex;gap:10px;flex-wrap:wrap;padding:0 12px 8px 12px;'>` +
                        item.deeplinkDetailList.map(link =>
                            `<div style='display:flex;align-items:center;gap:4px;background:#181818;padding:2px 8px 2px 2px;border-radius:6px;'>`+
                            (link.sourceIcon ? `<img src='${link.sourceIcon}' style='width:22px;height:22px;border-radius:4px;'>` : '')+
                            `<span style='color:#fff;font-size:0.97em;'>${link.sourceName||''}</span>`+
                            `<span style='color:#aaa;font-size:0.85em;'>#${link.sourceId||''}</span>`+
                            `</div>`
                        ).join('') + `</div>`;
                }
                // releaseTime 展示（格式化）
                let releaseTimeStr = '';
                if (item.releaseTime) {
                    const d = new Date(Number(item.releaseTime));
                    if (!isNaN(d.getTime())) {
                        const y = d.getFullYear();
                        const m = (d.getMonth()+1).toString().padStart(2,'0');
                        const day = d.getDate().toString().padStart(2,'0');
                        releaseTimeStr = `<div style='color:#6cf;font-size:0.92em;padding:0 12px 2px 12px;'>${y}-${m}-${day}</div>`;
                    }
                }
                // 卡片结构调整，duration放到发布日期上一行
                const $item = $(`
                    <div class="morelike-item" tabindex="0" style="background:#222;border-radius:10px;width:400px;min-width:400px;overflow:hidden;cursor:pointer;transition:transform 0.18s;">
                        <img src="${img}" alt="${title}" style="width:100%;height:225px;object-fit:cover;">
                        <div class="morelike-title">${title}</div>
                        ${categoriesStr}${videoScoresStr}
                        <div style='text-align:left;'>
                            ${seasonInfoStr}
                            ${durationStr}
                            ${releaseTimeStr}
                            ${valueStr}${deeplinkHtml}
                        </div>
                    </div>
                `);
                // 跳转到详情页
                $item.on('click', function() {
                    let valueStrParam = item.value ? (typeof item.value === 'string' ? item.value : JSON.stringify(item.value)) : '';
                    window.open(`video-detail.html?token=${encodeURIComponent(token)}&value=${encodeURIComponent(valueStrParam)}`, '_blank');
                });
                $('#morelikeList').append($item);
            });
        } catch (e) {
            $('#morelikeList').html('<div style="color:#aaa;padding:32px 0;">加载失败</div>');
        }
    }
    function renderMoreLikeThisCard(item) {
        // 只展示标题、时长、播放源
        const title = item.title || item.name || '';
        let duration = item.duration;
        if (item.moreInfo && item.moreInfo.duration) duration = item.moreInfo.duration;
        function formatDuration(d) {
            d = Number(d);
            if (isNaN(d) || d <= 0) return '';
            const h = Math.floor(d / 3600);
            const m = Math.floor((d % 3600) / 60);
            const s = d % 60;
            let arr = [];
            if (h > 0) arr.push(h + 'h');
            if (m > 0) arr.push(m + 'm');
            if (s > 0 || arr.length === 0) arr.push(s + 's');
            return arr.join(' ');
        }
        let durationStr = '';
        if (duration) {
            durationStr = `<div style='color:#ffd580;font-size:0.97em;padding:0 12px 2px 12px;'>${formatDuration(duration)}</div>`;
        }
        let deeplinkArr = (item.moreInfo && item.moreInfo.deeplinkDetailList) || item.deeplinkDetailList || [];
        let deeplinkHtml = '';
        if (Array.isArray(deeplinkArr) && deeplinkArr.length) {
            deeplinkHtml = `<div style='display:flex;gap:10px;flex-wrap:wrap;padding:0 12px 8px 12px;'>` +
                deeplinkArr.map(link =>
                    `<div style='display:flex;align-items:center;gap:4px;background:#181818;padding:2px 8px 2px 2px;border-radius:6px;'>`+
                    (link.sourceIcon ? `<img src='${link.sourceIcon}' style='width:22px;height:22px;border-radius:4px;'>` : '')+
                    `<span style='color:#fff;font-size:0.97em;'>${link.sourceName||''}</span>`+
                    `</div>`
                ).join('') + `</div>`;
        }
        const img = item.poster || item.icon || '';
        return `
            <div class="morelike-item" tabindex="0">
                <img src="${img}" alt="${title}">
                <div class="morelike-title">${title}</div>
                ${durationStr}
                ${deeplinkHtml}
            </div>
        `;
    }
    $(function(){
        loadVideoDetail();
        // 鼠标滚轮横向滚动
        $('.morelike-list').on('wheel', function(e) {
            if (e.originalEvent.deltaY === 0) return;
            this.scrollLeft += e.originalEvent.deltaY;
            e.preventDefault();
        });
    });
    </script>
</body>
</html> 